﻿using System.Collections.Generic;
using Minecraft.BLL.mysql;
using Minecraft.Config;
using Minecraft.Model;
using Minecraft.Model.AchievementItem;
using Minecraft.Model.ReqResp;

namespace Minecraft.ServerHall.Business
{
	public class AchievementBusiness
	{
		/// <summary>
		/// 
		/// </summary>
		/// <param name="session"></param>
		/// <param name="achievementConditionType">成就类型</param>
		/// <param name="conditionId">特定id（蓝图id、野怪id等）</param>
		/// <param name="num">数量</param>
		/// <returns></returns>
		public static void UpdateAchievementDetail(MinecraftSession session, EnumAchievementConditionType achievementConditionType, int conditionId = 0, int num = 1)
		{
			//1.
			var achievement = session.minecraftSessionInfo.playerAchievement;//
			var maybeAchievements = CsvConfig.achievementList.FindAll(t => t.ConditionType == achievementConditionType); // 此次玩家完成的这件事（击杀、解锁、升级等），可能符合哪些 成就

			var achievementItemList = ModAchievementItemInfo.ConvertStr2List(achievement.AchievementDetailStr);

			//2.
			var achiveStr = "";
			List<string> achieveList = new List<string>();
			for (int i = 0; i < achievementItemList.Count; i++)
			{
				var t = achievementItemList[i];

				var achieve = maybeAchievements.Find(m => m.AchievementId == t.AchievementId);

				var temp = "";
				if (achieve.ConditionType != achievementConditionType)
				{
					temp = $@"{t.AchievementId}#{t.FinishedNum}#{t.AwardGot}#{t.AwardGot}";
				}
				else
				{
					var finishNum = achieve.ConditionNum;
					if (t.FinishedNum + num < finishNum)
					{
						temp = $@"{t.AchievementId}#{t.FinishedNum + num}#{t.AwardGot}#{t.Status}";
					}
					else
					{
						temp = $@"{t.AchievementId}#{t.FinishedNum + num }#{t.AwardGot}#{(int)EnumAchievementStatus.Finished}";
					}
				}
				achieveList.Add(temp);
			}

			achiveStr = string.Join("|", achieveList);

			//更新内存中的
			achievement.AchievementDetailStr = achiveStr;
			
			//更新redis中的 、 更新mysql中的
			AchievementBLL.BatchUpdate(new List<AchievementModel>() { session.minecraftSessionInfo.playerAchievement }, session.minecraftSessionInfo.player.PlayerId, true);

		}




		/// <summary>
		/// 持久化用户在服务器内存中的成就信息
		/// </summary>
		/// <param name="session"></param>
		/// <returns></returns>
		public static BaseResp SaveAchievementsToDb(MinecraftSession session)
		{
			BaseResp resp = new BaseResp();

			if (session == null)
			{
				resp.RespLevel = RespLevelEnum.Error;
				resp.Msg = "session为null";
				return resp;
			}
			if (!session.minecraftSessionInfo.IsLogin)
			{
				resp.RespLevel = RespLevelEnum.Error;
				resp.Msg = "未登录";
				return resp;
			}

			//			AchievementBLL.BatchUpdate(session.minecraftSessionInfo.playerAchievementList, session.minecraftSessionInfo.player.PlayerId, true);


			return resp;
		}

	}
}
